package com.kzd.gtgame.main.game.adapter

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Rect
import android.graphics.Typeface
import android.text.Spannable
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.widget.*
import androidx.annotation.ColorRes
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.*
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.kzd.gtgame.db.GameDownload
import com.kzd.gtgame.R
import com.kzd.gtgame.custom.createViewGameImage
import com.kzd.gtgame.entity.*
import com.kzd.gtgame.main.toBargainDetailsActivity
import com.kzd.gtgame.main.toGameDetailsActivity
import com.kzd.gtgame.main.toMineRichTextActivityCon
import com.kzd.gtgame.main.toMineRichTextActivityUrl
import com.module.lemlin.image.loadImage
import com.module.lemlin.image.loadCircleImage
import com.module.lemlin.image.loadRoundImage
import com.youth.banner.adapter.BannerAdapter
import kotlinx.android.synthetic.main.activity_game_details.*
import java.lang.Exception
import java.text.DecimalFormat

class GameDownloadAdapter :
    BaseQuickAdapter<GameDownload, BaseViewHolder>(R.layout.item_game_download) {

    companion object {
        private const val GB: Long = 1024 * 1024 * 1024
        private const val MB: Long = 1024 * 1024
        private const val KB: Long = 1024

        fun bytes2kb(bytes: Long): String = when {
            bytes / GB >= 1 -> "${DecimalFormat("###.0").format(bytes / GB)}GB"
            bytes / MB >= 1 -> "${DecimalFormat("###.0").format(bytes / MB)}MB"
            bytes / KB >= 1 -> "${DecimalFormat("###.0").format(bytes / KB)}KB"
            else -> "${bytes}B"
        }
    }

    init {
        addChildClickViewIds(R.id.tvGameDownloadAction, R.id.tvGameDownloadDelete)
    }

    override fun convert(holder: BaseViewHolder, item: GameDownload) {
        holder.setText(R.id.tvGameDownloadName, item.gameName)
            .getView<ImageView>(R.id.ivGameDownloadIcon)
            .loadImage(item.gameIcon)

        holder.getView<ProgressBar>(R.id.pbDownloadProgress).apply {
            progress = item.progress
        }
        holder.getView<TextView>(R.id.tvGameDownloadAction).apply {
            text = if (item.downStatus == 0) {
                "暂停"
            } else if (item.downStatus == -1) {
                "等待"
            } else if (item.downStatus == 2) {
                "安装"
            } else if (item.downStatus == 4) {
                "打开"
            } else "继续"
        }
        holder.getView<TextView>(R.id.tvGameDownloadStatus).apply {
            text = if (item.downStatus == -1) {
                "等待中"
            } else if (item.downStatus == 1 || item.downStatus == 3) {
                "已暂停"
            } else if (item.downStatus == 2) {
                "可安装"
            } else if (item.downStatus == 4) {
                "可打开"
            } else "${item.progress}%"
        }
        holder.getView<TextView>(R.id.tvGameDownloadSpeed).apply {
            text = if (item.downStatus == 3) {
                "下载失败"
            } else if (item.downStatus == 2) {
                "下载完成"
            } else if (item.downStatus == 4) {
                "安装完成"
            } else {
                "${bytes2kb(item.currentSize)}/${bytes2kb(item.fileSize)}"
            }
        }
    }
}

/**
 * 游戏详情-图片适配器
 * */
class GameDetailsImageAdapter() :
    BaseQuickAdapter<String, BaseViewHolder>(0) {

    override fun onCreateDefViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder =
        BaseViewHolder(
            createViewGameImage(
                context,
                ConvertUtils.dp2px(125f),
                ConvertUtils.dp2px(205f)
            )
        )

    override fun convert(holder: BaseViewHolder, item: String) {
        (holder.itemView as ImageView)
            .loadRoundImage(item, radius = ConvertUtils.dp2px(15f))
    }
}

/**
 * 游戏福利-优惠券适配器
 * */
class GameWelfareCouponAdapter :
    BaseQuickAdapter<WelfareCoupon, BaseViewHolder>(R.layout.item_game_welfare_coupon) {

    override fun convert(holder: BaseViewHolder, item: WelfareCoupon) {

        holder.setText(R.id.tvWelfareCouponPrice, item.jian)
            .setText(
                R.id.tvWelfareCouponPriceFull, try {
                    if (item.money.toInt() == 0)
                        "任意金额" else "满${item.money}元可用"
                } catch (e: Exception) {
                    "任意金额"
                }
            )
            .setText(R.id.tvWelfareCouponDraw, if (item.is_draw) "领\n取" else "已\n领\n取")
        holder.getView<ImageView>(R.id.ivWelfareCouponBg).apply {
            if (item.is_draw) {
                setImageResource(R.mipmap.djj_wlq)
            } else {
                setImageResource(R.mipmap.djj_ylq)
            }
        }
        holder.itemView.tag = holder.layoutPosition
    }
}

/**
 * 游戏福利-活动适配器
 * */
class GameWelfareDoingAdapter :
    BaseQuickAdapter<WelfareDoing, BaseViewHolder>(R.layout.item_game_welfare_doing) {
    init {
        setOnItemClickListener { _, _, position ->
            val itemData = getItem(position)
            toMineRichTextActivityCon(itemData.title, itemData.content)
        }
    }

    override fun convert(holder: BaseViewHolder, item: WelfareDoing) {
        holder.setText(R.id.tvWelfareDoingLimit, item.limit_str)
            .setText(R.id.tvWelfareDoingStatus, item.statusStr)
            .setText(R.id.tvWelfareDoingTime, item.show_date)
            .setText(R.id.tvWelfareDoingDesc, item.description)
    }
}

/**
 * 游戏福利-礼包适配器
 * */
class GameWelfareGiftAdapter :
    BaseQuickAdapter<WelfareGift, BaseViewHolder>(R.layout.item_game_welfare_gift) {

    init {
        addChildClickViewIds(R.id.tvWelfareGiftGet)
    }

    override fun convert(holder: BaseViewHolder, item: WelfareGift) {
        holder.setText(R.id.tvWelfareGiftName, item.cardname)
            .setText(R.id.tvWelfareGiftContent, item.content)
        holder.getView<TextView>(R.id.tvWelfareGiftGet).apply {
            text = if (item.is_draw == 1) "已领取" else "领取"
            val drawable = if (item.is_draw == 1)
                R.drawable.bg_radius_20dp_gray2
            else R.drawable.bg_radius_20dp_main
            setBackgroundResource(drawable)
        }
    }
}

/**
 * 游戏详情-开服列表
 * */
class GameServiceAdapter :
    BaseQuickAdapter<GameService1, BaseViewHolder>(R.layout.item_game_service_remind) {
    init {
        addChildClickViewIds(R.id.tvGameServiceRemindStatus)
    }

    override fun convert(holder: BaseViewHolder, item: GameService1) {
        holder.setText(R.id.tvGameServiceRemindTime, item.time1)
            .setText(R.id.tvGameServiceRemindLabel, item.server_name)
            .setGone(R.id.tvGameServiceRemindStatus, item.game_id.isEmpty())
        holder.getView<TextView>(R.id.tvGameServiceRemindStatus).apply {
            isEnabled = item.type == 0
            text = when {
                item.type == 1 -> "已开服"
                item.remind_rs == 0 -> "提醒"
                else -> "取消提醒"
            }
        }
    }
}

/**
 * 游戏详情-交易
 * */

class GameBargainAdapter :
    BaseQuickAdapter<GameBargain, BaseViewHolder>(R.layout.item_game_bargain) {

    init {
        setOnItemClickListener { _, _, position ->
            val itemData = getItem(position)
            toBargainDetailsActivity(itemData.id)
        }
    }

    override fun convert(holder: BaseViewHolder, item: GameBargain) {
        holder.setText(
            R.id.tvGameBargainName,
            if (item.gameName.isNullOrEmpty()) item.sname else item.gameName
        )
            .setText(R.id.tvGameBargainDesc, item.name)
            .setText(R.id.tvGameBargainPrice, "￥${item.money}")
            .setText(
                R.id.tvGameBargainTime,
                StringBuilder().append("创建时间：").append(item.create_time)
            )
            .getView<ImageView>(R.id.ivGameBargainImage)
            .loadImage(item.images)
    }
}

/**
 * 游戏评论-组适配器
 * */
class GameDiscussGroupAdapter :
    BaseQuickAdapter<GameDiscuss, BaseViewHolder>(R.layout.item_game_discuss_group) {

    init {
        addChildClickViewIds(R.id.tvGameDiscussLike)
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    override fun convert(holder: BaseViewHolder, item: GameDiscuss) {
        holder.setText(R.id.tvGameDiscussUserName, item.user_name)
            .setText(R.id.tvGameDiscussContent, item.content)
            .setText(R.id.tvGameDiscussTime, item.time)
            .setText(
                R.id.tvGameDiscussCount,
                StringBuilder().append("共发表").append(item.comment_num).append("个游戏点评")
            )
            .setText(R.id.tvGameDiscussLike, item.zan)
            .setText(R.id.tvGameDiscussNumber, item.pinglun)

        holder.getView<TextView>(R.id.tvGameDiscussLike).apply {
            val left = resources.getDrawable(
                if (item.is_zan == 1) R.drawable.ic_10004 else R.drawable.ic_10003, null
            )
            left.setBounds(0, 0, left.minimumWidth, left.minimumHeight)
            setCompoundDrawables(left, null, null, null)
        }

        holder.getView<ImageView>(R.id.ivGameDiscussUserHead)
            .loadCircleImage(item.face)
        holder.getView<ImageView>(R.id.ivGameDiscussUserGarde)
            .loadImage(item.huiyuan_img)

        holder.getView<RecyclerView>(R.id.rvGameDiscussImageBody).apply {
            layoutManager = GridLayoutManager(context, 3)
            if (itemDecorationCount > 0)
                return@apply
            addItemDecoration(ItemDecoration())
        }.adapter = GameDiscussImageAdapter().apply {
            val imageStr = item.image
            if (imageStr.isNullOrEmpty()) {
                setNewInstance(mutableListOf())
            } else {
                setNewInstance(imageStr.split((",")).toMutableList())
            }
        }

        holder.getView<RecyclerView>(R.id.rvGameDiscussChildBody).apply {
            layoutManager = LinearLayoutManager(context)
        }.adapter = GameDiscussChildAdapter().apply {
            setNewInstance(item.pinglunlist.take(3).toMutableList())
            setOnItemClickListener { _, _, _ ->
                holder.itemView.performClick()
            }
            if (item.pinglunlist.size >= 3) {
                val view = createDiscussChildView(
                    context = this@GameDiscussGroupAdapter.context, color = R.color.colorMain,
                    content = "查看全部${item.pinglun}条评论>"
                )
                view.setOnClickListener {
                    holder.itemView.performClick()
                }
                setFooterView(view)
            } else {
                removeAllFooterView()
            }
        }
    }

    inner class ItemDecoration : RecyclerView.ItemDecoration() {
        override fun getItemOffsets(
            outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State
        ) {
            val position: Int = parent.getChildAdapterPosition(view)
            if (position == 0) {
                outRect.left = ConvertUtils.dp2px(0f)
            }
            if (position == state.itemCount - 1) {
                outRect.right = ConvertUtils.dp2px(0f)
            } else {
                outRect.right = ConvertUtils.dp2px(5f)
            }
            outRect.top = ConvertUtils.dp2px(5f)
            outRect.bottom = ConvertUtils.dp2px(5f)
        }
    }
}

/**
 * 游戏评论-回复适配器
 * */
class GameDiscussChildAdapter : BaseQuickAdapter<DiscussChild, BaseViewHolder>(0) {

    override fun onCreateDefViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder {
        return BaseViewHolder(createDiscussChildView(context, R.color.FF_999999))
    }

    override fun convert(holder: BaseViewHolder, item: DiscussChild) {
        val content = StringBuffer().append(item.user_name)
            .append(" 回复：").append(item.content)
        val spannable: Spannable = SpannableString(content)
        val span = ForegroundColorSpan(
            ColorUtils.getColor(R.color.colorMain)
        )
        spannable.setSpan(
            span, 0, item.user_name.length,
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        (holder.itemView as TextView).text = spannable
    }
}

/**
 * 游戏评论-回复适配器
 * */
class GameDiscussReplyAdapter :
    BaseQuickAdapter<GameDiscuss, BaseViewHolder>(R.layout.item_game_discuss_reply) {
    override fun convert(holder: BaseViewHolder, item: GameDiscuss) {
        holder.setText(R.id.tvDiscussReplyUserName, item.user_name)
            .setText(R.id.tvDiscussReplyTime, item.time)
            .setText(R.id.tvDiscussReplyContent, item.content)
            .getView<ImageView>(R.id.ivDiscussReplyUserHead)
            .loadCircleImage(item.face)
    }
}

/**
 * 游戏评论-图片适配器
 * */
class GameDiscussImageAdapter :
    BaseQuickAdapter<String, BaseViewHolder>(0) {
    override fun onCreateDefViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder =
        BaseViewHolder(createViewGameImage(context, height = ConvertUtils.dp2px(70f)))

    override fun convert(holder: BaseViewHolder, item: String) {
        (holder.itemView as ImageView).apply {
            scaleType = ImageView.ScaleType.CENTER_CROP
        }.loadRoundImage(item, radius = ConvertUtils.dp2px(5f))
    }
}

/**
 * 游戏评论-回复视图
 * */
fun createDiscussChildView(
    context: Context, @ColorRes color: Int, content: String? = null
): View = TextView(context).apply {
    layoutParams = FrameLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT).apply {
        this.topMargin = ConvertUtils.dp2px(2f)
        this.bottomMargin = ConvertUtils.dp2px(2f)
    }
    textSize = 13f
    text = content
    setTextColor(ColorUtils.getColor(color))
}


/**
 * 游戏分类标签
 * */
class GameClassifyAdapter :
    BaseQuickAdapter<ClassifyTab, BaseViewHolder>(R.layout.item_game_classify_tab) {
    var selectedPosition = 0
        set(value) {
            if (field != value) {
                field = value
                notifyDataSetChanged()
            }
        }

    override fun convert(holder: BaseViewHolder, item: ClassifyTab) {
        holder.getView<TextView>(R.id.tvGameClassifyTabName).apply {
            textSize = if (holder.layoutPosition == selectedPosition) {
                setTypeface(null, Typeface.BOLD)
                14f
            } else {
                setTypeface(null, Typeface.NORMAL)
                13f
            }
            text = item.name
        }
        holder.itemView.isSelected =
            holder.layoutPosition == selectedPosition
    }
}

/**
 * 游戏精选
 * */
class GameFeaturedAdapter :
    BaseQuickAdapter<GameGroup, BaseViewHolder>(R.layout.item_game_featured) {
    override fun convert(holder: BaseViewHolder, item: GameGroup) {
        holder.setText(R.id.tvGameFeaturedTitle, item.title)
            .getView<RecyclerView>(R.id.rvGameFeaturedBody).apply {
                this.layoutManager = GridLayoutManager(context, 3)
                this.setItemViewCacheSize(item.list.size)
//                this.setHasFixedSize(true)
                this.isNestedScrollingEnabled = false
            }.adapter = Game3Adapter().apply {
            setNewInstance(item.list)
        }
    }
}

/**
 * 游戏精选头部
 * */
class GameFeaturedSlideAdapter(games: MutableList<GameBean>) :
    BannerAdapter<GameBean, com.kzd.gtgame.base.BaseViewHolder>(games) {
    override fun onCreateHolder(
        parent: ViewGroup?, viewType: Int
    ): com.kzd.gtgame.base.BaseViewHolder {
        val view = LayoutInflater.from(parent?.context)
            .inflate(R.layout.item_game_featured_slide, parent, false)
        view.layoutParams = FrameLayout.LayoutParams(
            MATCH_PARENT, MATCH_PARENT
        ).apply {
            this.bottomMargin = ConvertUtils.dp2px(12f)
            this.topMargin = ConvertUtils.dp2px(12f)
            this.leftMargin = ConvertUtils.dp2px(7f)
            this.rightMargin = ConvertUtils.dp2px(7f)
        }
        return com.kzd.gtgame.base.BaseViewHolder(view)
    }

    override fun onBindView(
        holder: com.kzd.gtgame.base.BaseViewHolder?,
        data: GameBean, position: Int, size: Int
    ) {
        holder?.itemView?.findViewById<ImageView>(R.id.ivGameFeaturedSlideImage)
            ?.loadImage(src = data.image ?: R.mipmap.ic_80003, R.mipmap.ic_80003, R.mipmap.ic_80003)
        holder?.itemView?.findViewById<ImageView>(R.id.ivGameFeaturedSlideIcon)
            ?.loadImage(src = data.icon ?: R.mipmap.ic_80008, R.mipmap.ic_80008, R.mipmap.ic_80008)
        holder?.itemView?.findViewById<TextView>(R.id.tvGameFeaturedSlideName)
            ?.text = data.name
        holder?.itemView?.findViewById<TextView>(R.id.tvGameFeaturedSlideType)
            ?.text = java.lang.StringBuilder().append(data.type)
            .append("\t·\t").append(data.size).append("MB")

        val rvGameFeaturedSlideLabelBody = holder?.itemView
            ?.findViewById<RecyclerView>(R.id.rvGameFeaturedSlideLabelBody)
            ?: return
        val layoutManager = LinearLayoutManager(holder.itemView.context).apply {
            orientation = LinearLayoutManager.HORIZONTAL
        }
        rvGameFeaturedSlideLabelBody.layoutManager = layoutManager
        rvGameFeaturedSlideLabelBody.adapter = GameListLabelAdapter().apply {
            setNewInstance(data.biaoqian.toMutableList())
        }
    }
}


/**
 * 游戏条目列表标签
 * */
class GameListLabelAdapter(val style: Int = 0) : BaseQuickAdapter<String, BaseViewHolder>(0) {
    override fun onCreateDefViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder {
        return BaseViewHolder(createListLabelView(context, style = style))
    }

    override fun convert(holder: BaseViewHolder, item: String) {
        (holder.itemView as TextView).apply {
            if (style == 0) {
                val color = when (holder.layoutPosition) {
                    0 -> ColorUtils.getColor(R.color.FF_DE5256)
                    1 -> ColorUtils.getColor(R.color.FF_E0B35D)
                    else -> ColorUtils.getColor(R.color.colorMain)
                }
                setTextColor(color)
            } else {
                val drawable = when (holder.layoutPosition) {
                    0 -> R.drawable.bg_radius_02dp_label_1
                    1 -> R.drawable.bg_radius_02dp_label_2
                    else -> R.drawable.bg_radius_02dp_label_3
                }
                setBackgroundResource(drawable)
            }
        }.text = item
    }

    private fun createListLabelView(
        context: Context, style: Int = 0
    ): View = TextView(context).apply {
        layoutParams = FrameLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT).apply {
            this.rightMargin = ConvertUtils.dp2px(8f)
        }
        if (style == 0) {
            setPadding(0, 0, 0, 0)
        } else {
            setPadding(
                ConvertUtils.dp2px(4f),
                ConvertUtils.dp2px(1.5f),
                ConvertUtils.dp2px(4f),
                ConvertUtils.dp2px(1.5f)
            )
        }
        textSize = if (style == 0) 12f else 11f
        setTextColor(ColorUtils.getColor(if (style == 0) R.color.FF_999999 else R.color.white))
    }
}

/**
 * 玩过的游戏
 * */
class GamePlayedAdapter : BaseQuickAdapter<GamePlayed, BaseViewHolder>(R.layout.item_game_played) {
    override fun convert(holder: BaseViewHolder, item: GamePlayed) {
        holder.setText(R.id.tvGamePlayedName, item.name)
    }
}

/**
 * 玩过的游戏
 * */
class GameSmallAdapter : BaseQuickAdapter<GameSmall, BaseViewHolder>(R.layout.item_game_played) {
    override fun convert(holder: BaseViewHolder, item: GameSmall) {
        holder.setText(R.id.tvGamePlayedName, item.user_name)
    }
}


/**
 * 投诉反馈的游戏
 * */
class GameFeedbackAdapter :
    BaseQuickAdapter<GameFeedback, BaseViewHolder>(R.layout.item_game_played) {
    override fun convert(holder: BaseViewHolder, item: GameFeedback) {
        holder.setText(R.id.tvGamePlayedName, item.name)
    }
}


/**
 * 投诉反馈的游戏
 * */
class TransferGameAdapter :
    BaseQuickAdapter<Game, BaseViewHolder>(R.layout.item_game_played) {
    override fun convert(holder: BaseViewHolder, item: Game) {
        holder.setText(R.id.tvGamePlayedName, item.name)
    }
}

/**
 * 投诉反馈的游戏
 * */
class TransferRoleAdapter :
    BaseQuickAdapter<TransferRole, BaseViewHolder>(R.layout.item_game_played) {
    override fun convert(holder: BaseViewHolder, item: TransferRole) {
        holder.setText(R.id.tvGamePlayedName, item.role_name)
    }
}


/**
 * 游戏VIP
 * */
class GameVipAdapter : BaseQuickAdapter<GameVip, BaseViewHolder>(R.layout.item_game_details_vip) {
    override fun convert(holder: BaseViewHolder, item: GameVip) {
        holder.setText(R.id.tvGameDetailsVipName, item.name)
            .setText(R.id.tvGameDetailsVipRmb, item.`val`)
    }
}

class GamePresentAdapter :
    BaseQuickAdapter<GamePresent, BaseViewHolder>(R.layout.item_game_present) {

    init {
        setOnItemClickListener { _, _, position ->
            val itemData = data[position]
            toGameDetailsActivity(itemData.gid)
        }
    }

    override fun convert(holder: BaseViewHolder, item: GamePresent) {
        holder.setText(R.id.tvGamePresentName, item.name)
            .setText(
                R.id.tvGamePresentNum,
                java.lang.StringBuilder().append("礼包数：").append(item.lb_num)
            )
            .getView<ImageView>(R.id.ivGamePresentIcon)
            .loadImage(src = item.icon ?: R.mipmap.ic_80008, R.mipmap.ic_80008, R.mipmap.ic_80008)
    }
}